package controller

import (
	"a-common/myerr"
	"a-system/domain/entity"
	"a-system/service"
	"sync"

	"github.com/gofiber/fiber/v2"
)

var (
	noticeControllerTemp *NoticeController
	sysNoticeService     = service.NewSysNoticeService()
	noticeControllerOnce sync.Once
)

type NoticeController struct{}

func NewSysNoticeController() *NoticeController {
	noticeControllerOnce.Do(func() {
		noticeControllerTemp = &NoticeController{}
	})
	return noticeControllerTemp
}

// List 列表
func (m *NoticeController) List(c *fiber.Ctx) error {
	var args entity.SysNoticeDto
	// 解析并绑定参数到结构体
	if err := c.QueryParser(&args); err != nil {
		return myerr.ERR_SYS_ARGS
	}
	err := args.Validator()
	if err != nil {
		return err
	}

	rows, err := sysNoticeService.List(&args)
	if err != nil {
		return err
	}

	return Resp(c, rows)
}

// Get 查
func (m *NoticeController) Get(c *fiber.Ctx) error {
	data, err := sysNoticeService.Get(c.Params("id"))
	if err != nil {
		return err
	}

	return Resp(c, data)
}

// Del 删
func (m *NoticeController) Del(c *fiber.Ctx) error {
	ids := c.Params("ids")
	if ids == "" {
		return myerr.ERR_SYS_ARGS
	}
	_, err := sysNoticeService.Del(ids)
	if err != nil {
		return err
	}
	return Ok(c)
}

// Add 增
func (m *NoticeController) Add(c *fiber.Ctx) error {
	var args entity.SysNoticeDto
	if err := c.BodyParser(&args); err != nil {
		return myerr.ERR_SYS_ARGS
	}
	user := GetUser(c)
	args.CreatedBy = user.Account

	_, err := sysNoticeService.Add(&args)
	if err != nil {
		return err
	}
	return Ok(c)
}

// Edit 改
func (m *NoticeController) Edit(c *fiber.Ctx) error {
	var args entity.SysNoticeDto
	if err := c.BodyParser(&args); err != nil {
		return myerr.ERR_SYS_ARGS
	}
	user := GetUser(c)
	args.UpdatedBy = user.Account

	_, err := sysNoticeService.Edit(&args)
	if err != nil {
		return err
	}
	return Ok(c)
}
